/*
 * @Author: Setsuna
 * @Email: 601890383@qq.com
 * @FilePath: \src\pages\QuotaManage\ManualInventoryRecord\components\AddStockFormModal.tsx
 * @Date: 2021-11-29 17:51:46
 * @LastEditTime: 2023-05-23 23:11:19
 */

import UdSelect from '@/components/UdFormControls/UdSelect'
import { http, UdForm, validators } from '@/lib'
import udMainStore from '@/store/UdMain'
import React from 'react'
import { DatePicker, TreeSelect, Select, message } from 'antd'
import { TreeNodeValue } from 'antd/lib/tree-select/interface'
import apis from '@/apis/AboutQuota'
import defaultApis from '@/apis'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import { formUtils } from '@/lib/utils/formUtils'
const { Option } = Select
const { RangePicker } = DatePicker
const { TreeNode } = TreeSelect

export default class AddStock extends React.Component<any> {
  // 隐藏掉头曲二曲
  // public hideArr: any = ['头曲', '二曲', '泸州老窖头曲酒类销售有限公司', '泸州老窖二曲酒类销售有限公司']
  // public brandList = udMainStore.brandList.filter(item => this.hideArr.indexOf(item.title) === -1)
  public brandList = udMainStore.brandList
  private form: WrappedFormUtils = null as any
  state = {
    customerList: [],
    treeDataList: [],
    parentCodeList: [],//分销商
    item: []
  }

  componentDidMount() {
    this.setState({ item: this.formItem() })
    this.props.getHandler && this.props.getHandler(this.getResult)
    this.getAreaList(this.brandList[0].value)
  }

  //片区改变事件,根据片区查询客户
  private getCustomerByAreaCode = (belongAreaCode: TreeNodeValue) => {
    this.form.setFieldsValue({
      dealerCode: undefined,
      parentCode: undefined,
    })
    this.setState({ customerList: [], parentCodeList: [] }, () => {
      http
        .get(apis.getAgentInfoList, {
          params: { belongAreaCode },
        })
        .then(res => {
          const { data: customerList } = res
          let customerListRe = customerList.map(({ agentCode, agentName }) => ({ value: agentCode, title: agentName }))
          this.setState({ customerList: customerListRe }, () => {
            this.setState({ item: this.formItem() })
          })
        })
    })
  }

  //处理片区树数据
  private mapTree = (data: any[]) => {
    return data.map(item => {
      return (
        <TreeNode value={item.code} title={item.name} key={item.code}>
          {this.mapTree(item?.children || [])}
        </TreeNode>
      )
    })
  }

  //获取片区
  private getAreaList = (value?: any) => {
    if (Object.is(value, undefined)) return [];
    http.get(defaultApis.getTreeByUser, {
      params: { organizationCode: value },
    }).then(res => {
      let treeDataList = res?.data?.children || []
      this.setState({ treeDataList }, () => {
        this.setState({ item: this.formItem() })
      })
    })
  }

  public getResult = () => {
    return new Promise((resolve, reject) => {
      this.form.validateFieldsAndScroll((errors, values) => {
        if (errors) {
          reject(errors)
          return
        }
        let finalValues = formUtils.handleValues(values)
        // 公司品牌
        if (finalValues['brandCode']) finalValues["brandNameShort"] = `${this.brandList.find(e => e.value == finalValues['brandCode']).title} ${finalValues['brandCode']}`;
        // 经销商
        if (finalValues['dealerCode']) finalValues["dealerName"] = `${this.state.customerList.find(e => e.value == finalValues['dealerCode']).title} ${finalValues['dealerCode']}`;
        // 盘点时间
        if (finalValues['inventoryTime']) finalValues["description"] = finalValues['inventoryTime'].map(e => e.format('yyyyMMDD')).join('-');
        // 分销商
        if (finalValues['dealerType'] && Object.is(finalValues['dealerType'], 'DISTRIBUTOR')) {
          let { parentCode, dealerCode } = JSON.parse(JSON.stringify(finalValues));
          // 经销商code -parentCode
          finalValues['parentCode'] = dealerCode;
          //  经销商名称-parentName
          finalValues["parentName"] = `${this.state.customerList.find(e => e.value == dealerCode).title} ${dealerCode}`;
          //  分销商code - dealerCode
          finalValues['dealerCode'] = parentCode;
          //  分销商name - dealerName
          finalValues["dealerName"] = `${this.state.parentCodeList.find(e => e.value == parentCode).title} ${parentCode}`;
        }
        resolve(finalValues)
      })
    })
  }

  /**
   * 切换品牌公司
   */
  private changeBrandCode = (value: any, callBack?: Function) => {
    this.form.setFieldsValue({
      transferArea: undefined,
      dealerCode: undefined,
      parentCode: undefined,
    })
    this.setState({ treeDataList: [], customerList: [], parentCodeList: [] }, () => {
      Promise.allSettled([this.getAreaList(value)]).then((res: any) => {
        this.setState({
          treeDataList: res[0]?.value || [],
        })
      })
    })
  }

  // 字符串转驼峰
  private convertToCamelCase = (str: any) => {
    var strArr = str.split("");
    return strArr.map((e, index) => Object.is(index, 0) ? e.toUpperCase() : e.toLowerCase()).join("");
  }

  /**
   * 切换经销商带出分销商
   * @param e 
   */
  private dealerCodeSelect = (e: any) => {
    let { brandCode, dealerType } = this.form.getFieldsValue();
    if (dealerType == undefined || dealerType == null || dealerType == '') {//分销商类型选择的时候选择经销商品品类型的选择，不){
      message.info("请选择客户类型！！")
      return;
    } else {
      dealerType = this.convertToCamelCase(dealerType);
    }
    this.form.setFieldsValue({
      parentCode: undefined,
    })
    this.setState({ parentCodeList: [] }, () => {
      http.get(defaultApis.getDealerLowerLevel, {
        params: {
          size: 99999, page: 1,
          acctCode: e,
          mdmCompanyCode: brandCode,
          // acctType: '',
          acctType: dealerType || '',
        },
      }).then(res => {
        let { content } = res.data;
        let contentList = content.map(({ acctCode, acctName }) => ({ value: acctCode, title: acctName }))
        this.setState({ parentCodeList: contentList }, () => {
          this.setState({ item: this.formItem() })
        })
      })
    })
  }

  /**
   * 切换客户类型
   * @param e 
   */
  private dealerTypeSelect = (e: any) => {
    this.setState({
      // customerList: [],
      // parentCodeList: [],
    }, () => {
      this.setState({ item: this.formItem() })
    })
  }

  private formItem = () => {
    let fItem = [
      {
        label: '品牌公司',
        id: 'brandCode',
        rules: [validators.required],
        initialValue: this.brandList[0].value,
        render: <UdSelect showSearch allowClear={false} options={this.brandList} onChange={value => {
          this.changeBrandCode(value)
        }} />,
      },
      {
        label: '盘点时间',
        id: 'inventoryTime',
        rules: [validators.required],
        render: (
          <RangePicker
            style={{ width: '100%' }}
            format="YYYY-MM-DD"
          />
        ),
      },
      {
        id: 'transferArea',
        label: '所属管辖区域',
        rules: [validators.required],
        render: (
          <TreeSelect
            showSearch
            treeNodeFilterProp="title"
            onChange={(value, label, extra) => {
              this.getCustomerByAreaCode(value)
            }}
          >
            {this.mapTree(this.state.treeDataList)}
          </TreeSelect>
        ),
      },
      {
        id: 'dealerType',
        label: '客户类型',
        rules: [validators.required],
        render: () => (
          <Select placeholder="请选择状态" onChange={e => this.dealerTypeSelect(e)}>
            <Option value="DEALER">经销商</Option>
            <Option value="DISTRIBUTOR">分销商</Option>
          </Select>
        ),
      },
      {
        id: 'dealerCode',
        label: '经销商',
        rules: [validators.required],
        render: <UdSelect showSearch options={this.state.customerList} onChange={e => this.dealerCodeSelect(e)} />,
      },
    ];
    if (this.form) {
      let { dealerType } = this.form?.getFieldsValue();
      if (Object.is(dealerType, 'DISTRIBUTOR')) {
        fItem.push({
          id: 'parentCode',
          label: '分销商',
          rules: [validators.required],
          render: <UdSelect showSearch options={this.state.parentCodeList} />,
        })
      } else {
        fItem = fItem.filter(e => e.id !== 'parentCode');
      }
    }
    return fItem;
  }

  render() {
    return (
      <UdForm
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 18 }}
        getForm={e => {
          this.form = e
          if (this.props.getForm) {
            this.props.getForm(e)
          }
        }}
        items={this.state.item}
      />
    )
  }
}
